﻿@page "/"
@using System.Text.Json
@using WeatherApp.Dtos
@using WeatherApp.Models
@inject IJSRuntime JSRuntime
@inject ILogger<Home> Logger
<PageTitle>Home</PageTitle>


<div class="container">
    <div class="row">
        <div class="col-md-6 offset-3">
            <div class="input-group">
                <input @bind="weatherCity" type="text" placeholder="Search for a city..." class="form-control" id="weatherCity">
                <button class="btn btn-outline-secondary"
                        @onclick="()=>CheckWeatherAsync(weatherCity)">
                    Check weather
                </button>
                @if (isShowFavorite)
                {
                    <button class="btn btn-outline-secondary" onclick="favoriteCity()">Favorite @CityName</button>
                }
            </div>

            <hr />
            @if (weatherResponse != null && weatherResponse.Results != null)
            {
                <div class="card text-center">
                    <div class="card-header" id="weather_city">
                        @weatherResponse.Results[0].Location.Name
                    </div>
                    <div class="card-body">
                        <p class="card-text" id="weather_forecast">@weatherResponse.Results[0].Now.Text</p>
                        <p class="card-text" id="weather_temperature">
                            @weatherResponse.Results[0].Now.Temperature &#176;
                        </p>

                    </div>
                </div>
            }

        </div>
    </div>
</div>


@code {
    private string weatherCity = "";
    private static bool isShowFavorite = false;
    private static string CityName = "";
    private DotNetObjectReference<Home> dotnetHelper;

    private WeatherResponse weatherResponse = new();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // await JSRuntime.InvokeVoidAsync("alert", "Hello");
            // await JSRuntime.InvokeVoidAsync("localStorage.setItem", "welcometxt", "Hello world");

            dotnetHelper = DotNetObjectReference.Create(this);
            await JSRuntime.InvokeVoidAsync("jsHelper.setDotNetHelper", dotnetHelper);

            await JSRuntime.InvokeVoidAsync("import", "/scripts/custom.js");

            Logger.LogInformation("custom.js was imported");
        }

        try
        {
            throw new Exception("Exception happended");
        }
        catch (Exception ex)
        {
            Logger.LogError(ex.Message);
        }
    }

    protected async Task CheckWeatherAsync(string cityName)
    {
        // 调用没有返回的 js 方法
        //await JSRuntime.InvokeVoidAsync("checkWeather",cityName);

        // 有返回的 js 方法
        weatherResponse = await JSRuntime.InvokeAsync<WeatherResponse>("checkWeather", cityName);
    }

    [JSInvokable]
    public static async Task ShowFavoriteButton(string cityName)
    {
        CityName = cityName;
        isShowFavorite = true;
    }

    [JSInvokable]
    public async Task FavoriteCity()
    {
        //Get all items
        //var items = await JSRuntime.InvokeAsync<List<FavoritedCity>>("localStorage.getItem", "favoriteCities");
        var items = JsonSerializer.Deserialize<List<FavoritedCity>>(await JSRuntime.InvokeAsync<string>("localStorage.getItem", "favoriteCities"));

        if (items == null)
        {
            items = new List<FavoritedCity>();
            //Update the list
            items.Add(new FavoritedCity()
                {
                    Id = 1,
                    CityName = CityName
                });
        }
        else
        {
            items.Add(new FavoritedCity
                {
                    Id = items.Count + 1,
                    CityName = CityName
                });
        }

        //Set new item
        await JSRuntime.InvokeVoidAsync("localStorage.setItem", "favoriteCities", JsonSerializer.Serialize(items));
    }
}

<script>

    var jsHelper = {};
    jsHelper.setDotNetHelper = function (helper) {
        jsHelper.dotnetHelper = helper;
    }

    function favoriteCity() {
        jsHelper.dotnetHelper.invokeMethodAsync('FavoriteCity');
    }
</script>